package com.rc.saas.tenant.controller.invite;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.invite.MemberInviteSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.ticket.TenantTicketType;
import com.rc.saas.tenant.search.invite.InviteSearch;
import com.rc.saas.tenant.service.invite.MemberInviteLinkService;
import com.rc.saas.tenant.service.invite.MemberInviteSettingService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.invite.InviteSettingVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

@Controller
@RequestMapping("/inviteTicket")
public class InviteTicketController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String sessionInvitePrefix = "invite";

    @Autowired
    private MemberInviteSettingService memberInviteSettingService;

    @Autowired
    private TenantTicketTypeService ticketTypeService;

    @Autowired
    private MemberInviteLinkService memberInviteLinkService;

    /**
     * 跳转邀请有奖页面
     * 奖励类型 1返利   2赠送优惠券
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "templates/invite/inviteTicketList";
    }

    /**
     * 返邀请有奖列表数据统计
     *
     * @return
     */
    @RequestMapping(value = "/inviteTicketList", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo inviteTicketList(InviteSearch inviteSearch) {
        PageInfo<InviteSettingVo> pageInfo = memberInviteSettingService.listPageInviteTicket(inviteSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转邀请有奖优惠券详情
     * @return
     */
    @RequestMapping(value = "/detailInviteTicket/{inviteSettingId}", method = RequestMethod.GET)
    public String detailInviteTicket(@PathVariable("inviteSettingId") Long inviteSettingId, Model model) {
        MemberInviteSetting memberInviteSetting = memberInviteSettingService.selectByPrimaryKey(inviteSettingId);

        List<TenantTicketType> tenantTicketTypes = ticketTypeService.listTenantTicketType(memberInviteSetting.getTenantCode());
        StringBuilder sb = new StringBuilder();
        for (TenantTicketType tenantTicketType : tenantTicketTypes) {
            String ticketDetail = "";
            //优惠类型,0立减 1打折 默认0
            if ("0".equals(tenantTicketType.getDiscountType())) {
                ticketDetail = "满" + tenantTicketType.getUseRequireAmount() + "立减" + tenantTicketType.getDiscountAmount();
            } else {
                ticketDetail = "满" + tenantTicketType.getUseRequireAmount() + "享"
                        + tenantTicketType.getDiscount().multiply(BigDecimal.TEN).setScale(2) + "折";
            }
            sb.append("<option value=\"");
            sb.append(tenantTicketType.getTicketTypeId() + "\"");
            sb.append(" data-ticketName=\"");
            sb.append(ticketDetail);
            sb.append("\"");
            if (tenantTicketType.getTicketTypeId().equals(memberInviteSetting.getTicketTypeId())) {
                sb.append("\" selected >");
            } else {
                sb.append("\">");
            }
            sb.append(tenantTicketType.getTicketName());
            sb.append("</option>");
        }

        model.addAttribute("ticketSelect", sb.toString());
        //model.addAttribute("tenantTicketTypes", tenantTicketTypes);
        model.addAttribute("memberInviteSetting", memberInviteSetting);
        return "templates/invite/detailInviteTicket";
    }


    @RequestMapping(value = "/addInviteTicket", method = RequestMethod.GET)
    public String addInviteTicket(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantTicketType> tenantTicketTypes = ticketTypeService.listTenantTicketType(user.getTenantCode());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tenantTicketTypes.size(); i++) {
            TenantTicketType tenantTicketType = tenantTicketTypes.get(i);
            String ticketDetail = "";
            //优惠类型,0立减 1打折 默认0
            if ("0".equals(tenantTicketType.getDiscountType())) {
                ticketDetail = "满" + tenantTicketType.getUseRequireAmount() + "立减" + tenantTicketType.getDiscountAmount();
            } else {
                ticketDetail = "满" + tenantTicketType.getUseRequireAmount() + "享"
                        + tenantTicketType.getDiscount().multiply(BigDecimal.TEN).setScale(2) + "折";
            }
            sb.append("<option value=\"");
            sb.append(tenantTicketType.getTicketTypeId() + "\"");
            sb.append(" data-ticketName=\"");
            sb.append(ticketDetail);
            sb.append("\"");
            if (i == 0) {
                sb.append("\" selected >");
            } else {
                sb.append("\">");
            }
            sb.append(tenantTicketType.getTicketName());
            sb.append("</option>");
        }

        //model.addAttribute("tenantTicketTypes", tenantTicketTypes);
        model.addAttribute("ticketSelect", sb.toString());

        return "templates/invite/addInviteTicket";
    }

    /**
     * 禁止方案
     *
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(Long inviteSettingId) {
        memberInviteSettingService.updateStatus(inviteSettingId);
        return TResponse.SUCCESS();
    }

    /**
     * 新增或更改
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateMemberInviteSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateMemberInviteSetting(MemberInviteSetting memberInviteSetting) {
        logger.info("memberInviteSetting入参为:{}", memberInviteSetting.toString());
        TenantUser user = ShiroUtils.getSessionUser();
        if (!BeanUtil.isValid(memberInviteSetting.getInviteName(),
                memberInviteSetting.getInviteType(), memberInviteSetting.getTicketTypeId(),
                memberInviteSetting.getBeginTime(), memberInviteSetting.getEndTime(), memberInviteSetting.getTicketTypeCount())) {
            return TResponse.FAIL("参数不能为空");
        }
        if (memberInviteSetting.getInviteName().length() > 20) {
            return TResponse.FAIL("活动名称不能大于20字符");
        }

        if (!"2".equals(memberInviteSetting.getInviteType())) {
            return TResponse.FAIL("类型不正确:" + memberInviteSetting.getInviteType());
        }

        if (memberInviteSetting.getTicketTypeCount() > 99) {
            return TResponse.FAIL("单次赠送数量不超过100");
        }

        if (!BeanUtil.isValid(memberInviteSetting.getTicketTypeCount(),
                memberInviteSetting.getTicketTypeId())) {
            return TResponse.FAIL("优惠券参数不正确");
        }

        if (!BeanUtil.isValid(memberInviteSetting.getBeginTime(),
                memberInviteSetting.getEndTime())) {
            return TResponse.FAIL("起止时间不能为空");
        }
        if (memberInviteSetting.getBeginTime().getTime()>memberInviteSetting.getEndTime().getTime()){
            return TResponse.FAIL("开始时间大于结束时间");
        }

        if (memberInviteSetting.getInviteRemark() != null && memberInviteSetting.getInviteRemark().length() > 50) {
            return TResponse.FAIL("邀请描述不能超过50字符");
        }

        if (memberInviteSetting.getTenantCode() == null) {
            memberInviteSetting.setTenantCode(user.getTenantCode());
        }
        memberInviteSettingService.insertOrUpdateMemberInviteSetting(memberInviteSetting);
        return TResponse.SUCCESS();
    }


    /**
     * 跳转邀请有奖页面
     * 奖励类型 1赠送优惠券  2返利
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/inviteLink/{inviteSettingId}", method = RequestMethod.GET)
    public String inviteLink(Model model, @PathVariable("inviteSettingId") Long inviteSettingId) {
        model.addAttribute("inviteSettingId", inviteSettingId);
        return "templates/invite/inviteLinkList";
    }

}
